package service.impl;

import dao.FaciDao;
import dao.impl.FaciDaoImpl;
import entity.Faci;
import service.FaciService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FaciServiceImpl implements FaciService {
    FaciDao faciDao = new FaciDaoImpl();

    public Map<String, Object> searchAll(int page, int limit) {

        Map<String, Object> result = new HashMap<>();

        List<Faci> list = faciDao.getAllFaci(page, limit);
        int count = faciDao.getCountByFaci();
        System.out.println(count);
        result.put("data", list);
        result.put("count", count);
        result.put("code", 0);
        return result;
    }

    public Map<String, Object> saveFaci(Faci faci) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            if (!faciDao.select(faci)) {
                map.put("success", faciDao.insert(faci));
            } else {
                map.put("success", faciDao.update(faci));
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("success", false);
            map.put("msg", "操作失败!");
        }
        return map;
    }

    @Override
    public Map<String, Object> deleteFaci(String id) {
        Map<String,Object> map=new HashMap();
        String[] strs = id.split(",");

        List<Integer> list = new ArrayList<>();

        for(int i = 0;i < strs.length;i ++){
            list.add(Integer.parseInt(strs[i]));
        }
        if(list.size() > 1 ){
            if (faciDao.deleteByIds(list)){
                map.put("success",true);
                map.put("msg", "批量删除成功");
            }
            else {
                map.put("success",false);
                map.put("msg", "批量删除失败");
            }
        }else if(list.size() == 1 ){
            if (faciDao.deleteById(list)){
                map.put("success",true);
                map.put("msg", "删除成功");
            }
            else{
                map.put("success",false);
                map.put("msg", "删除失败");
            }
        }

        return map;
    }

}

